import { defineEventHandler, readBody } from "h3";
import { verifyCode } from "../../services/verificationService";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { email, code } = body;

    // 数据验证
    if (!email || !code) {
      return {
        success: false,
        error: "邮箱和验证码不能为空",
      };
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return {
        success: false,
        error: "邮箱格式不正确",
      };
    }

    // 验证验证码
    const verificationResult = verifyCode(email, code);

    return {
      success: verificationResult.success,
      message: verificationResult.message,
      ...(verificationResult.success && { verified: true })
    };
  } catch (error) {
    console.error('验证验证码错误:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "验证验证码失败",
    };
  }
});
